package com.android.readcard.read;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.global.ConstantsValue;
import com.android.readcard.global.PrefReadCardTools;
import com.android.readcard.inter.UpLoadListener;
import com.android.readcard.utils.BleGlobUtils;
import com.android.readcard.utils.UploadCardUtils;
import com.sunrise.icardreader.helper.ConsantHelper;
import com.sunrise.icardreader.model.IdentityCardZ;
import com.sunrise.reader.ReaderManagerService;

import sunrise.bluetooth.SRBluetoothCardReader;

/**
 * 森锐读卡
 * 2017/8/24
 * 张鹏
 */
public class SenRuiConnectUtils {

    private BluetoothDevice remoteDevice;
    private String bleAddress;
    private String bleName;
    private Context context;
    private Activity activity;
    private String name, sex, nation, id_num, address, sign_office, to, from, born;
    private String birth_year, birth_month, birth_day, sign_data, photoHeard;
    private Bitmap photo;
    private String bluetoothName = "";
    // 注册成功失败监听
    private UpLoadListener mOnUpLoadListener;
    private SRBluetoothCardReader SenmBlueReaderHelper;
    boolean isRegisterBT = false;
    public IdentityCardZ SenmIdentityCardZ;
    //回调handler
    public static Handler uiHandler;
    private String bluetoothType;

    private String srAccount = "test01";
    private String srPwd = "12315aA..1";
    private String srKey = "FE870B0163113409C134283661490AEF";

    private String sn = "";//森锐串码

    public SenRuiConnectUtils(final Context context, String bluetoothType, BluetoothDevice remoteDevice,
                              final String bleName, final String bleAddress, final String bluetoothName,
                              String srAccount, String srPwd, String srKey, final UpLoadListener mOnUpLoadListener) {
        this.context = context;
        this.activity = (Activity) context;
        this.bluetoothType = bluetoothType;
        this.remoteDevice = remoteDevice;
        this.bleName = bleName;
        this.bleAddress = bleAddress;
        this.bluetoothName = bluetoothName;
        this.srAccount = srAccount;
        this.srPwd = srPwd;
        this.srKey = srKey;
        this.mOnUpLoadListener = mOnUpLoadListener;
        uiHandler = new MyHandler(activity);

        // 连接森锐服务器
        SenmBlueReaderHelper = new SRBluetoothCardReader(uiHandler, activity, srAccount,
                srPwd, srKey);

    }

    /**
     * 连接
     */
    public void connect() {

        if (remoteDevice.getBondState() == BluetoothDevice.BOND_NONE) {
            // 未配对
            setErr("该设备未配对");
        } else {
            senRuiRead();
        }
    }

    private void setErr(String err) {
        mOnUpLoadListener.onErrUpLoad(4, err);
    }

    private void senRuiRead() {
        //连接设备
        new Thread(new Runnable() {
            public void run() {
                //连接设备
                isRegisterBT = SenmBlueReaderHelper.registerBlueCard(bleAddress);
                uiHandler.sendEmptyMessage(REGISTER_BLUETOOTH);
            }
        }).start();
    }

    private static final int REGISTER_BLUETOOTH = 50;

    /**
     * 断开连接
     */
    public void stopConnect() {
        try {
            ReaderManagerService.stopServer();
            Log.e("阅读", "------森锐断开连接------");
        } catch (Exception e) {
            Log.e("项目异常", "------断开连接异常------" + e.toString());
            setErr("断开连接异常");
            e.printStackTrace();
        }

    }

    /**
     * 消息handle,包括绑定蓝牙消息、绑定OTG消息、读身份证结果返回消息
     */
    class MyHandler extends Handler {
        private Activity mActivity;

        @SuppressLint("HandlerLeak")
        MyHandler(Activity activity) {
            this.mActivity = activity;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //成功
                case ConsantHelper.READ_CARD_SUCCESS:
                    handleReturnSuccessMsg(msg);
                    break;
                //错误-1
                case ConsantHelper.READ_CARD_NO_READ:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-2
                case ConsantHelper.READ_CARD_BUSY:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-3
                case ConsantHelper.READ_CARD_NET_ERR:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-4
                case ConsantHelper.READ_CARD_NO_CARD:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-5
                case ConsantHelper.READ_CARD_SAM_ERR:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-6
                case ConsantHelper.READ_CARD_OTHER_ERR:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-7
                case ConsantHelper.READ_CARD_NEED_TRY:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-8
                case ConsantHelper.READ_CARD_OPEN_FAILED:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-9
                case ConsantHelper.READ_CARD_NO_CONNECT:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-10
                case ConsantHelper.READ_CARD_NO_SERVER:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-11
                case ConsantHelper.READ_CARD_FAILED:
                    handleReturnErrorMsg(msg);
                    break;
                //错误-12
                case ConsantHelper.READ_CARD_SN_ERR:
                    handleReturnErrorMsg(msg);
                    break;
                //开始交互身份证
                case ConsantHelper.READ_CARD_START:
                    Log.e("阅读", "------森瑞开始读卡-----");
                    break;
                //绑定蓝牙
                case REGISTER_BLUETOOTH:
                    if (isRegisterBT) {
                        //开始读身份证
                        new Thread() {
                            public void run() {
                                Log.e("阅读", "------2------" + "");
                                //蓝牙读身份证
                                String sn = PrefReadCardTools.getString(context, ConstantsValue.SRDEVICESN, "SR620170102829");
                                if (sn != null && !TextUtils.isEmpty(sn)) {
                                    Log.e("项目异常sn", "------sn------" + sn);
                                    SenmBlueReaderHelper.c.deviceSn(sn);
                                    SenmBlueReaderHelper.c.setReaderSN(sn);
                                }
                                SenmBlueReaderHelper.readCard(30);
                            }
                        }.start();
                    } else {
                        Toast.makeText(context, "请确认蓝牙设备已经连接，再读卡!", Toast.LENGTH_LONG).show();
                    }
                    break;
                //进度
                case ConsantHelper.READ_CARD_PROGRESS:
                    Log.e("阅读", msg.obj.toString());
                    break;
            }
        }
    }

    /**
     * 森锐返回错误信息后的处理
     */
    private void handleReturnErrorMsg(Message message) {
        String err = (String) message.obj;
        setErr(err + "");
    }

    /**
     * 森锐返回成功信息后的处理
     */
    private void handleReturnSuccessMsg(Message message) {
        SenmIdentityCardZ = (IdentityCardZ) message.obj;
        readCardSuccess2((IdentityCardZ) message.obj);
    }

    /**
     * 森锐读卡成功信息提交
     */
    private void readCardSuccess2(IdentityCardZ SenmIdentityCardZ) {

        if (SenmIdentityCardZ != null) {
            Log.e("阅读", "------读卡成功------");
            photo = BitmapFactory.decodeByteArray(SenmIdentityCardZ.avatar, 0,
                    SenmIdentityCardZ.avatar.length);
            photoHeard = BleGlobUtils.bitmaptoString(photo); //头像
            name = SenmIdentityCardZ.name.trim(); //名字
            sex = SenmIdentityCardZ.sex; //性别
            nation = SenmIdentityCardZ.ethnicity; //民族
            born = SenmIdentityCardZ.birth.trim();  //出生年月日
            birth_year = SenmIdentityCardZ.birth.substring(0, 4);
            birth_month = SenmIdentityCardZ.birth.substring(4, 6);
            birth_day = SenmIdentityCardZ.birth.substring(6, 8);

            address = SenmIdentityCardZ.address.trim();//地址
            id_num = SenmIdentityCardZ.cardNo.trim();//证件号 身份证号
            sign_office = SenmIdentityCardZ.authority.trim();//签发机关
            from = SenmIdentityCardZ.period.substring(0, 4) +
                    SenmIdentityCardZ.period.substring(4, 6) +
                    SenmIdentityCardZ.period.substring(6, 8);
            if (SenmIdentityCardZ.period.contains("长期")) {
                to = "长期";
                sign_data = SenmIdentityCardZ.period.substring(0, 4) + "." +
                        SenmIdentityCardZ.period.substring(4, 6) + "." +
                        SenmIdentityCardZ.period.substring(6, 8) + "--" + "长期";
            } else {
                to = SenmIdentityCardZ.period.substring(9, 13) +
                        SenmIdentityCardZ.period.substring(13, 15) +
                        SenmIdentityCardZ.period.substring(15, 17);
                sign_data = SenmIdentityCardZ.period.substring(0, 4) + "." +
                        SenmIdentityCardZ.period.substring(4, 6) + "." +
                        SenmIdentityCardZ.period.substring(6, 8) + "--" +
                        SenmIdentityCardZ.period.substring(9, 13) + "." +
                        SenmIdentityCardZ.period.substring(13, 15) + "." +
                        SenmIdentityCardZ.period.substring(15, 17);
            }
            String chuanMa = UploadCardUtils.getChuanMa(bleName, bleAddress);// 获取串码
// 获取身份证数据
            ReadCardInfo cardInfo = UploadCardUtils.getCardInfo(bluetoothName, address, photoHeard, sex, id_num, nation,
                    sign_office, to, name, from, born, sign_data, birth_year,
                    birth_month, birth_day, photo);

            // 获取读卡上传数据,使用时需要把data转换成json和串码一起上传
            CardData cardData = UploadCardUtils.getData(bluetoothType, address, photoHeard, sex, id_num, nation,
                    sign_office, to, name, from, born, sign_data, birth_year,
                    birth_month, birth_day, photo);

            mOnUpLoadListener.onSucUpLoad(cardInfo, cardData, chuanMa);
        } else {
            setErr("读取失败,SenmIdentityCardZ为空");
        }
    }
}
